﻿using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO; 
using MyLib;
 
namespace PerformanceReport.AjaxPage
{
    /// <summary>
    /// GenerateReports 的摘要说明
    /// </summary>
    public class GenerateAvgReports : IHttpHandler 
    {
        string strSql;
        string strJson;
        string strPara;
        string strStartDate;
        string strEndDate;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            strPara = context.Request["Para"];             //流程名
            strStartDate = context.Request["StartDate"];     //开始时间
            strEndDate = context.Request["EndDate"];       //结束时间
 
            string strSql = " Select max(ProcessVersion) as Ver ,ProcessName, "         //得到最大的版本号（即最新版本号）
                              + "avg(datediff(hour,starttime,endtime)) as Hours "
                              + "  from Incidents";
            string where = " where 1=1 ";
            where += " and ProcessName like N'" + strPara.Trim() + "%'";
            if (!string.IsNullOrEmpty(strStartDate))
            {
                where += " and  starttime >= '" + strStartDate.Trim() + "'";
            }
            if (!string.IsNullOrEmpty(strEndDate))
            {
                where += " and  starttime <= '" + strEndDate.Trim() + "'";
            }
            
            where += "  group by ProcessName  order by ProcessName";
            string StrSqlTotal = strSql + where;
            DataTable dt = DataAccess.Instance("UltDB").ExecuteDataTable(StrSqlTotal.ToString());


            //如果存在返回值的情况
            if (dt.Rows.Count > 0)
            {
               
                string strProcessName = InitProcessName(dt);
                string strAvgDay = ProcessAvgDay(dt);

                strJson = "[";

                //循环所有的行
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                strJson += "{'ProcessName':'" + CheckText(strProcessName.Trim()) + "',"
                        + "'AvgDay':'" + CheckText(strAvgDay.Trim()) + "'},";
                
                //}
                strJson = strJson.Substring(0, strJson.LastIndexOf(','));
                strJson += "]";
            }

            context.Response.Buffer = true;
            context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            context.Response.Expires = 0;
            context.Response.CacheControl = "no-cache";
            context.Response.Write(strJson);
        }

        //平均耗时
        public string TotalAvgDay(DataTable dt)
        {
            string strHtmlCount = string.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string strSql = "select  ProcessVersion,ProcessName,starttime,endtime,INCIDENT, "
                             + "ROUND(TO_NUMBER(to_date(endtime) - to_date(starttime))) as Days"
                             + " from INCIDENTS"
                             + " where ProcessName like N'%" + dt.Rows[i]["ProcessName"].ToString() + "%'"
                             + " and INCIDENT='" + dt.Rows[i]["INCIDENT"].ToString() + "'";
                            
                DataTable dtCount = DataAccess.Instance("BizDB").ExecuteDataTable(strSql.ToString());
                if (dtCount.Rows.Count > 0)
                {
                    for (int j = 0; j < dtCount.Rows.Count; j++)
                    {
                        //四舍五入,保留一位有效数字
                        if (dtCount.Rows[j]["Days"].ToString() != "")
                        {
                            dtCount.Compute("SUM([Days])", "true").ToString();
                            double Day = double.Parse(dtCount.Rows[j]["Days"].ToString());
                            double strAvgDay = Math.Round(Day, 1, MidpointRounding.AwayFromZero);                          
                            strHtmlCount += strAvgDay + ",";
                        }
                    }
                }
                else
                {
                    strHtmlCount += "0" + ",";
                }
            }

            //拼接series值
            string strHeader = "{ type: 'column',name:'天'" + "," + "data:" + "[";  
            string strEnd = "]}";           
            string strTotal = strHeader + strHtmlCount.TrimEnd(',') + strEnd;         
            return strTotal;          
        }

        public string AvgDay(DataTable dt)
        {
            //拼接series值
            string strHeader = "{ type: 'column',name:'天'" + "," + "data:" + "[";
            string strEnd = "]}";           
            string strData = dt.Rows[0]["Days"].ToString();
            string strTotal = strHeader + strData + strEnd;
            return strTotal;
 
        }

        //流程名称
        public string InitProcessName(DataTable dt)
        {
            string strHtml = string.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strHtml += dt.Rows[i]["ProcessName"].ToString().Trim() + ",";
            }
            return strHtml;        
        }

        //流程平均耗时
        public string ProcessAvgDay(DataTable dt)
        {
            string strData = string.Empty;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["Hours"].ToString() != "")
                {                    
                    strData += GetAvgDay(dt.Rows[i]["Hours"].ToString()).Trim() + ",";
                }
                else
                {
                    strData += "0" + ",";
                }
            }

            //拼接series值
            string strHeader = "{ type: 'column',name:'平均天数'" + "," + "data:" + "[";
            string strEnd = "]}";
            string strTotal = strHeader + strData.TrimEnd(',') + strEnd;
            return strTotal;

        }
        //转换平均消耗（小时）为平均消耗（天）
        public string GetAvgDay(string strHour)
        {
            string strAvgDay = null;
            if (strHour != "")
            {
                double dDay = double.Parse(strHour);
                double dAvgDay = Math.Round(dDay / 24, 0, MidpointRounding.AwayFromZero);
                strAvgDay = dAvgDay.ToString();
            }
            return strAvgDay;

        }

        public string CheckText(string Str)
        {
            string ReturnString = "";
            ReturnString = Str.Replace(",", "#dou#");
            ReturnString = Str.Replace("'", "#dan#");
            return ReturnString;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
         
    }
}